package com.wechat.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class ImageDownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("收到请求");
        ServletInputStream inputStream = request.getInputStream();
        byte[] buffer = new byte[1024];
        int a = -1;
        String rootPath = getServletContext().getRealPath("/");
        String resourcePath = rootPath+"resources/HeadPic/";
        String filePath = new Date().getTime()+".jpg";          //文件通过时间戳来取名
        System.out.println(rootPath);
        System.out.println(resourcePath);
        File file = new File(resourcePath+filePath);
        FileOutputStream fs = new FileOutputStream(file);
        int sumLen = 0;

        while ((a = inputStream.read(buffer)) != -1){
            fs.write(buffer,0,a);
            sumLen += a;
            System.out.println(sumLen);
        }
        fs.flush();
        inputStream.close();
        fs.close();
        String netPath = "http://192.168.2.102:8080/WechatServer/resources/HeadPic/"+filePath;
        response.getWriter().write(netPath);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
